#include "board.h"
#include "AHT20.h"
#include "bflb_gpio.h"

struct bflb_device_s *gpio;

typedef enum
{
	LED_STA_OFF = 0,   /* 关闭 */
	LED_STA_ON,        /* 打开 */
	LED_STA_LAST,
}LedSta;

void LED_Init()
{
	/* 初始化绿灯，用来指示LED状态 */
	gpio = bflb_device_get_by_name("gpio");
    bflb_gpio_init(gpio, GPIO_PIN_14, GPIO_OUTPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_0);
}

void LED_SetSta(LedSta _Sta)
{
	if (_Sta)
	{
		/* 高电平打开LED */
		bflb_gpio_set(gpio, GPIO_PIN_14);
	}
	else
	{
		/* 低电平关闭LED */
		bflb_gpio_reset(gpio, GPIO_PIN_14);
	}
}
int main(void)
{
	int32_t AHT20ReadTempAndHumi[2] = {0};
	LedSta LEDSta = LED_STA_ON;
	
	board_init();    /* 板卡初始化 */
	LED_Init();      /* LED初始化 */
	if(AHT20_INIT_RES_OK == AHT20_Init())
	{
		/* AHT20初始化成功 */
		printf("AHT20 Init OK\r\n");
	}
	else
	{
		/* AHT20初始化失败 */
		printf("AHT20 Init Err!!!\r\n");
	}
	LED_SetSta(LEDSta);
    while (1) 
	{
        /* 读取 ATH20 传感器状态 */
        while(AHT20_STA_ERR == AHT20_ReadSta())
        {
			/* 重新初始化AHT20 */
            AHT20_Init();           
            bflb_mtimer_delay_ms(30);
        }
		/* 获取温湿度数据 */
		if (AHT20_READ_OK == AHT20_RecTempAndHumiVal(AHT20ReadTempAndHumi))
		{
			/* 获取成功 */
			printf("AHT20 Read Temperature is:%.1f,Humidity is %.1f\r\n",(float)AHT20ReadTempAndHumi[1]/10, (float)AHT20ReadTempAndHumi[0]/10);
		}
		else
		{
			/* 获取失败 */
			printf("Read Err!!!\r\n");
		}
		bflb_mtimer_delay_ms(1000);
		/* LED状态翻转，用来识别MCU是否正常工作 */
		if (LED_STA_ON == LEDSta)
		{
			LEDSta = LED_STA_OFF;
		}
		else
		{
			LEDSta = LED_STA_ON;
		}
		
		LED_SetSta(LEDSta);
    }
}
